<template>
  <el-drawer
    :title="
      drawerType === '0'
        ? '通知规则设置'
        : drawerType === '1'
        ? '通知规则编辑'
        : '通知规则详情'
    "
    :visible.sync="drawerVisible"
    :wrapperClosable="false"
    :direction="drawerDirection"
    :size="drawerSize"
    @open="mountMethod"
    :destroy-on-close="true"
    :before-close="handleBeforeClose"
    :show-close="false"
  >
    <el-form
      label-width="100px"
      :model="form"
      :disabled="
        drawerType === '2' ||
        (drawerType === '1' && form.trigger_conditions !== '') ||
        form.status === '1'
      "
    >
      <el-form-item label="通知内容">
        <el-input
          type="textarea"
          style="width: 81%"
          v-model="form.notice_content"
        ></el-input>
      </el-form-item>
      <el-form-item label="通知角色">
        <el-select
          @change="changeRules"
          v-model="form.notice_role"
          placeholder="请选择"
          style="margin-right: 10px"
        >
          <el-option label="角色" value="1"></el-option>
          <el-option label="收货人" value="2" disabled></el-option>
          <el-option label="发货人" value="3" disabled></el-option>
          <el-option label="账号" value="4"></el-option>
          <el-option label="特定人员" value="5" disabled></el-option>
        </el-select>
        <el-select
          clearable
          filterable
          v-if="form.notice_role === '1'"
          v-model="form.notice_role_detail"
          multiple
          placeholder="请选择"
          style="width: 405px"
        >
          <el-option
            :label="item.name"
            :value="item.id"
            v-for="item in rolesList"
            :key="item.id"
          ></el-option>
        </el-select>
        <el-input
          v-if="form.notice_role === '4'"
          style="width: 200px"
          placeholder="请输入帐号"
          v-model="form.notice_role_detail"
        ></el-input>
      </el-form-item>
      <el-form-item label="通知方式">
        <el-select
          v-model="form.notice_method"
          multiple
          clearable
          placeholder="请选择"
        >
          <el-option label="站内信" value="1"></el-option>
          <el-option label="小程序服务通知" value="2" disabled></el-option>
          <el-option label="短信" value="3" disabled></el-option>
          <el-option label="微信公众号" value="4" disabled></el-option>
          <el-option label="电话" value="5" disabled></el-option>
          <el-option label="飞书" value="6" disabled></el-option>
        </el-select>
      </el-form-item>
      <el-form-item
        label="触发条件"
        v-if="form.trigger_conditions"
        style="padding-right: 140px"
        >{{ form.trigger_conditions }}</el-form-item
      >
      <el-form-item label="点击跳转">
        <el-radio-group v-model="form.jump_type">
          <el-radio label="0">无</el-radio>
          <el-radio label="1"
            >指定链接
            <el-input
              v-if="form.jump_type === '1'"
              style="width: 70%; margin-left: 10px"
              v-model="form.jump_link"
              placeholder="请输入指定链接"
            ></el-input
          ></el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="通知频率">
        <el-radio-group v-model="form.notice_type">
          <el-radio label="0">立即通知</el-radio>
          <el-radio label="1"
            >定时通知
            <el-date-picker
              v-if="form.notice_type === '1'"
              style="margin-left: 10px; width: 180px"
              v-model="form.notice_time"
              type="datetime"
              placeholder="选择日期时间"
              value-format="timestamp"
              :picker-options="pickerOptions"
            ></el-date-picker
          ></el-radio>
          <el-radio label="2"
            >周期通知<el-button
              style="margin-left: 10px"
              :class="{ 'is-active': form.cycle_type === '1' }"
              @click="form.cycle_type = '1'"
              >日</el-button
            >
            <el-button
              @click="form.cycle_type = '2'"
              :class="{ 'is-active': form.cycle_type === '2' }"
              >周</el-button
            >
            <el-button
              @click="form.cycle_type = '3'"
              :class="{ 'is-active': form.cycle_type === '3' }"
              >月</el-button
            >
            <el-select
              v-model="form.cycle_number"
              v-if="form.cycle_type === '2' && form.notice_type === '2'"
              style="margin-left: 10px; width: 80px"
              placeholder="请选择"
            >
              <el-option
                v-for="(item, index) in weekDays"
                :key="index"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
            <el-select
              placeholder="请选择"
              v-model="form.cycle_number"
              v-if="form.cycle_type === '3' && form.notice_type === '2'"
              style="margin-left: 10px; width: 80px"
            >
              <el-option
                v-for="(item, index) in monthDays"
                :key="index"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
            <el-time-picker
              arrow-control
              v-if="form.notice_type === '2'"
              style="margin-left: 10px; width: 110px"
              v-model="scheduleTime"
              type="datetime"
              placeholder="选择时间"
              value-format="HH-m"
            ></el-time-picker>
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="通知说明">
        <el-input
          style="width: 81%"
          type="textarea"
          v-model="form.notice_desc"
        ></el-input>
      </el-form-item>
      <el-form-item label="状态">{{
        form.status === "0"
          ? "草稿"
          : form.status === "1"
          ? "启用"
          : form.status === "2"
          ? "禁用"
          : ""
      }}</el-form-item>
    </el-form>
    <div style="margin-left: 40%" v-if="drawerType === '0'">
      <el-button @click="handleSaveDraft">保存草稿</el-button>
      <el-button type="danger" @click="handleDisable" v-if="form.status === '1'"
        >禁用</el-button
      >
      <el-button type="success" @click="handleSubmit" v-else>启用</el-button>
      <el-button @click="handleBeforeClose">关闭</el-button>
    </div>
    <div style="margin-left: 40%" v-if="drawerType === '1'">
      <el-button
        @click="handleSaveDraft"
        v-if="form.trigger_conditions === '' && form.status === '2'"
        >保存草稿</el-button
      >
      <el-button type="danger" @click="handleDisable" v-if="form.status === '1'"
        >禁用</el-button
      >
      <el-button type="success" @click="handleSubmit" v-else>启用</el-button>
      <el-button @click="handleBeforeClose">关闭</el-button>
    </div>
    <div style="margin-left: 45%" v-if="drawerType === '2'">
      <el-button @click="handleBeforeClose">关闭</el-button>
    </div>
  </el-drawer>
</template>

<script>
import {
  reqMessageRulesCreate,
  reqMessageRulesDetail,
  reqMessageRulesUpdate,
  reqMessageRulesStatus,
} from "@/api/companymanagement";
import { roleList } from "@/api/organization";

export default {
  name: "createMessageRule",
  props: ["drawerVisible", "drawerType", "id"],
  data() {
    return {
      drawerDirection: "rtl",
      drawerSize: "60%",
      form: {
        notice_content: "", // 通知内容
        notice_desc: "", // 通知说明
        notice_role: "1", // 通知角色 1角色 2收货人 3发货人
        notice_role_detail: "", // 通知角色详情
        jump_type: "0", // 跳转方式 0不跳转 1跳转详情 2指定链接
        jump_link: "", // 跳转链接
        notice_method: ["1"], // 通知方式 1站内信 2小程序服务通知, 3短信 4微信公众号 5电话 6飞书, 多种以逗号隔开
        notice_type: "0", // 通知频率 0立即通知 1定时通知 2周期通知',
        notice_time: "", // 通知时间 时间戳
        cycle_type: "", // 周期类型 1日 2周 3月
        cycle_number: "", // 周期类型所对应 周为1到7 月为1到31
        hour: "", // 小时 对应周期循环的小时
        minute: "", // 分钟 对应周期循环的分钟
        status: "0", // 状态 0草稿 1启用 2禁用
      },
      pickerOptions: {
        shortcuts: [
          {
            text: "今天",
            onClick(picker) {
              picker.$emit("pick", new Date());
            },
          },
          {
            text: "昨天",
            onClick(picker) {
              const date = new Date();
              date.setTime(date.getTime() - 3600 * 1000 * 24);
              picker.$emit("pick", date);
            },
          },
          {
            text: "一周前",
            onClick(picker) {
              const date = new Date();
              date.setTime(date.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit("pick", date);
            },
          },
        ],
      },
      rolesList: [],
      scheduleTime: "",
    };
  },
  computed: {
    weekDays() {
      return [
        { label: "周日", value: "7" },
        { label: "周一", value: "1" },
        { label: "周二", value: "2" },
        { label: "周三", value: "3" },
        { label: "周四", value: "4" },
        { label: "周五", value: "5" },
        { label: "周六", value: "6" },
      ];
    },
    monthDays() {
      const data = [];
      for (let i = 1; i <= 31; i++) {
        data.push({ label: i + "号", value: i + "" });
      }
      return data;
    },
  },
  methods: {
    mountMethod() {
      this.getRolesList();
      if (this.drawerType !== "0") this.getRuleDetail();
    },
    async getRuleDetail() {
      let result = await reqMessageRulesDetail({
        id: this.id,
      });
      this.form = result.data;
      this.form.notice_role_detail =
        this.form.notice_role_detail !== ""
          ? this.form.notice_role_detail.split(",").map((item) => item * 1)
          : "";
      this.form.notice_method = this.form.notice_method.split(",");
      this.form.notice_time = this.form.notice_time * 1000;
      this.scheduleTime = this.form.hour + "-" + this.form.minute;
      this.form.cycle_number =
        this.form.cycle_number !== "0" ? this.form.cycle_number : "";
    },
    changeRules(val) {
      if (val !== "1") {
        this.form.notice_role_detail = "";
      }
    },
    async getRolesList() {
      let res = await roleList({
        name: "",
      });
      this.rolesList = res.data.list || [];
    },
    handleBeforeClose(done) {
      Object.assign(this.$data, this.$options.data());
      this.$parent.closeDialog();
    },
    async createRulesSetting() {
      const {
        notice_content,
        notice_desc,
        notice_role,
        notice_role_detail,
        jump_type,
        jump_link,
        notice_method,
        notice_type,
        notice_time,
        cycle_type,
        cycle_number,
        status,
      } = this.form;
      const data = {
        notice_content,
        notice_desc,
        notice_role,
        notice_role_detail:
          notice_role === "1" ? notice_role_detail.join(",") : "",
        jump_type,
        jump_link,
        notice_method: notice_method.join(","),
        notice_type,
        notice_time: notice_type === "1" ? (notice_time + "").slice(0, 10) : "",
        cycle_type: notice_type === "2" ? cycle_type : "",
        cycle_number: cycle_type !== "1" ? cycle_number : "",
        hour: this.scheduleTime.split("-")[0],
        minute: this.scheduleTime.split("-")[1],
        status,
      };
      let res = await reqMessageRulesCreate(data);
      if (res.code === 10000) {
        this.$message({
          message: "保存成功",
          type: "success",
        });
      } else {
        this.$message({
          message: res.message,
          type: "error",
        });
      }
      this.handleBeforeClose();
      this.$parent.getList();
    },
    async updateRulesSetting() {
      const {
        notice_content,
        notice_desc,
        notice_role,
        notice_role_detail,
        jump_type,
        jump_link,
        notice_method,
        notice_type,
        notice_time,
        cycle_type,
        cycle_number,
        status,
      } = this.form;
      const data = {
        id: this.id,
        notice_content,
        notice_desc,
        notice_role,
        notice_role_detail:
          notice_role === "1" ? notice_role_detail.join(",") : "",
        jump_type,
        jump_link,
        notice_method: notice_method.join(","),
        notice_type,
        notice_time: notice_type === "1" ? (notice_time + "").slice(0, 10) : "",
        cycle_type: notice_type === "2" ? cycle_type : "",
        cycle_number: cycle_type !== "1" ? cycle_number : "",
        hour: this.scheduleTime.split("-")[0],
        minute: this.scheduleTime.split("-")[1],
        status,
      };
      let res = await reqMessageRulesUpdate(data);
      if (res.code === 10000) {
        this.$message({
          message: "保存成功",
          type: "success",
        });
      } else {
        this.$message({
          message: res.message,
          type: "error",
        });
      }
      // this.handleBeforeClose();
      this.$parent.getList();
    },
    async updateStatus(id, val) {
      let res = await reqMessageRulesStatus({
        id: id,
        status: val,
      });
      if (res.code === 10000) {
        this.$message({
          message: (val === "1" ? "启用" : "禁用") + "成功",
          type: "success",
        });
      } else {
        this.$message({
          message: res.message,
          type: "error",
        });
      }
    },
    handleSubmit() {
      //启用
      this.form.status = "1";
      if (this.drawerType === "0") {
        this.createRulesSetting();
      } else if (
        this.drawerType === "1" &&
        this.form.trigger_conditions === ""
      ) {
        this.updateRulesSetting();
      } else {
        this.updateStatus(this.id + "", this.form.status);
        // this.handleBeforeClose();
        // setTimeout(() => {
        //   this.$parent.getList();
        // }, 1000);
      }
    },
    handleSaveDraft() {
      //草稿
      this.form.status = "0";
      if (this.drawerType === "0") {
        this.createRulesSetting();
      } else if (
        this.drawerType === "1" &&
        this.form.trigger_conditions === ""
      ) {
        this.updateRulesSetting();
      } else {
        this.updateStatus(this.id + "", this.form.status);
        // this.handleBeforeClose();
        // setTimeout(() => {
        //   this.$parent.getList();
        // }, 1000);
      }
    },
    handleDisable() {
      //禁用
      this.form.status = "2";
      if (this.drawerType === "0") {
        this.createRulesSetting();
      } else if (
        this.drawerType === "1" &&
        this.form.trigger_conditions === ""
      ) {
        this.updateRulesSetting();
      } else {
        this.updateStatus(this.id + "", this.form.status);
        // this.handleBeforeClose();
        // setTimeout(() => {
        //   this.$parent.getList();
        // }, 1000);
      }
    },
  },
};
</script>

<style lang="less" scoped>
/deep/ .el-form-item {
  margin-bottom: 25px;
}
.el-button.is-active {
  background-color: #dcdcdc;
  border-color: #dcdcdc;
  color: #333;
}
</style>